//
//  HomeViewController.swift
//  PhotoBrowser
//
//  Created by 林彬 on 16/4/28.
//  Copyright © 2016年 linbin. All rights reserved.
//

import UIKit
import Foundation
import MJExtension
import SDWebImage

private let ID = "HomeCell"

class HomeViewController: UICollectionViewController {
   // MARK:- 懒加载模型数组
    private lazy var shopArr : [Shop] = [Shop]()
    
//    var photoBrowserVc = PhotoBrowserViewController()
    
    // MARK:- 懒加载转场动画代理对象
    private lazy var photoBrowserAnimator = PhotoBrowserAnimator()
    
    // MARK:- 加载控制器
    override func viewDidLoad() {
        super.viewDidLoad()
        
        getNetData(0)
    }
    
    
}

// MARK:- 请求网络数据
extension HomeViewController{
    func getNetData(offset : Int) {
        LBNetWorkTool.shareNetWorkTool.getHomeViewNetData(offset) { (result, error) -> () in

            // 获得那边传递过来的result和error
            
            // 1:还是要做判断
            if error != nil {
                print(error)
                return
            }
            
            // 2:数据类型不对
            guard let resultArray = result as? [[String : AnyObject]] else{
                print(NSError(domain: "error data", code: -1011, userInfo: nil))
                return
            }
            
            // 3:遍历返回过来的字典数组
            for resultDict in resultArray {
                let shop = Shop(dict: resultDict)
                
                self.shopArr.append(shop)
            }
            
            // 4:刷新表格
            self.collectionView?.reloadData()
        }
    }
}

// MARK:- 弹出图片浏览器
extension HomeViewController{

    /// 展示图片浏览器
    private func showPhotoBrowser(indexPath : NSIndexPath) {
        // 1.创建图片浏览器的控制器
        let photoBrowserVc = PhotoBrowserViewController()
        
        // 2.给photoBrowserVc设置属性
        photoBrowserVc.indexPath = indexPath
        photoBrowserVc.shopArr = shopArr
        
        // 3.设置modal样式
        photoBrowserVc.modalPresentationStyle = .Custom
        photoBrowserVc.transitioningDelegate = photoBrowserAnimator
        
        // 4.给photoBrowserAnimator设置值
        photoBrowserAnimator.indexPath = indexPath
        photoBrowserAnimator.presentDelegate = self
        photoBrowserAnimator.dismissDelegate = photoBrowserVc
        
        // 5.弹出图片浏览器
        presentViewController(photoBrowserVc, animated: true, completion: nil)
        
        // 6:闭包回调
       rollingCollection(photoBrowserVc)

  
    }
}

// MARK:- 闭包回调
/*
如果cell是点击出图片浏览器,再滑动,更新后的cell,又可能滑动到homeview里未显示的cell,再dismiss的话会报错.
解决方案,是在PhotoBrowserAnimator里作用滑动的时候,把当前cell的indexPath通过闭包传到HomeViewController.
如果indexPath对应的cell的y值大于屏幕高度或者小于0,那么HomeViewController自动将这个cell滚动到中间位置
但是这样的话,获取将HomeViewController中cell的坐标换成windew中的坐标的话,就不能用获取cell,再convertRect这方法了.
需要用layout取
*/
extension HomeViewController {
    // 6.回调闭包
    private func rollingCollection(photoBrowserVc : PhotoBrowserViewController) {
        //     获得PhotoBrowserViewController中的indexPath
        photoBrowserVc.getIndexPath { (imageVIndexPath) -> () in

            // 把imageVIndexPath对应的cell的坐标转换成当前window里面的坐标
            let currentCellFrame : CGRect = self.homeRect(imageVIndexPath)
            
            if currentCellFrame.origin.y > UIScreen.mainScreen().bounds.size.height  || currentCellFrame.maxY < 0 {
                
                self.collectionView?.scrollToItemAtIndexPath(imageVIndexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredVertically, animated: false)
            }
        }
    }
}


// MARK:- 实现presentDelegate中的方法
extension HomeViewController : PresentDelegate {
    func homeRect(indexPath: NSIndexPath) -> CGRect {
        // 1.取出cell
//        let cell = (collectionView?.cellForItemAtIndexPath(indexPath) as? HomeCell)!
//
//        // 2.将cell的frame转成cell如果是在window中坐标
//        let homeFrame = collectionView!.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
//        
//        return homeFrame
        
        
        // 2.如果cell是点击出图片浏览器,再滑动,更新后的cell,又可能滑动到homeview里未显示的cell
        // 再dismiss的话会报错.
        // 根据layOut来取
        let layOut = collectionView?.collectionViewLayout as! HomeViewFolwLayout
        var homeNewFrame = layOut.layoutAttributesForItemAtIndexPath(indexPath)?.frame
        homeNewFrame?.origin.x += collectionView!.contentInset.left
        homeNewFrame?.origin.y -= collectionView!.contentOffset.y
        return homeNewFrame!
        
    }
    
    func photoBrowserRect(indexPath: NSIndexPath) -> CGRect {
        
        // 1.取出cell
        let cell = (collectionView?.cellForItemAtIndexPath(indexPath))! as! HomeCell
        
        // 2.取出cell中显示的图片
        let image = cell.imageView.image
        
        // 3.计算image放大之后的frame
        return calculateFrame(image!)
    }
    
    func imageView(indexPath: NSIndexPath) -> UIImageView {
        
        // 1.创建imageView对象
        let imageView = UIImageView()
        
        // 2.设置显示的图片
        // 2.1.取出cell
        let cell = (collectionView?.cellForItemAtIndexPath(indexPath))! as! HomeCell
        
        // 2.2.取出cell中显示的图片
        let image = cell.imageView.image
        
        // 2.3.设置图片
        imageView.image = image
        
        // 3.设置imageView的属性
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        
        return imageView
    }
}

// MARK:- 数据源函数
extension HomeViewController{
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return shopArr.count
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        // 要加上 as! HomeCell 相当于OC中用自定义的cell来创建对象.
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ID, forIndexPath: indexPath) as! HomeCell
        cell.backgroundColor = UIColor.yellowColor()
        cell.shop = shopArr[indexPath.item]
        
        // 如果显示到的是最后一个数据,那么再加载30个
        if indexPath.item == shopArr.count - 1 {
            getNetData(shopArr.count)
        }
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        showPhotoBrowser(indexPath)
    }
}


